import axios from 'axios'
import {ElMessage,ElLoading} from 'element-plus'
import store from '@/store'
import router from '@/router'
let VUE_APP_BASE_API = process.env.VUE_APP_BASE_API;
if (process.env.NODE_ENV === 'production') {
    const baseApiMap = {
        'd-partner-portal.lifeat.cn': 'https://d-partner-cms-api.lifeat.cn:45788',
        't-partner-portal.lifeat.cn': 'https://t-partner-cms-api.lifeat.cn:45788',
        'h-partner-portal.lifeat.cn': 'https://h-partner-cms-api.lifeat.cn:45788',
        'partner-portal.lifeat.cn': 'https://partner-cms-api.lifeat.cn',
    }
    VUE_APP_BASE_API = baseApiMap[location.hostname]
}
console.log('VUE_APP_BASE_API:', VUE_APP_BASE_API)
let loadingInstance = null;
if (VUE_APP_BASE_API === 'https://partner-cms-api.lifeat.cn') {
    // 生产  禁用调console
    window.console.log = () => { }
}
const service = axios.create({
    baseURL: VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 60000 // request timeout
})
// request interceptor
service.interceptors.request.use(
    config => {
        if (store.getters.token) {
            config.headers['Authorization'] = 'Bearer ' + store.getters.token
            config.headers['Content-Type'] = 'application/json'
        }
        // 判断是否需要loading, 默认需要loading  不需要loadding传入isNoLoading为true
        if (!config.isNoLoading) {
            loadingInstance = ElLoading.service({
                lock: true,
                text: '努力加载中…',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0)',
                customClass: 'global-loading'
            });
        }
        return config
    },
    error => {
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        loadingInstance && loadingInstance.close();
        const res = response.data
        const config = response.config
        if (res.code === 402 ||
             res.code === 100 ||
             res.code === 102 ||
             res.code === 103 ||
             res.code === 406
        ) {
            !config.isNoTip && ElMessage({
                message: res.msg || 'Error',
                type: 'info',
                duration: 2 * 1000
            })
            localStorage.removeItem('userPhone')
            setTimeout(() => {
                router.push('/login')
            }, 2000)
        } else if (res.code !== 200) {
            if (!config.isNoTip) {
                ElMessage({
                    message: res.msg || 'Error',
                    type: 'error',
                    duration: 5 * 1000
                })
            }
            return Promise.reject(new Error(res.msg || 'Error'))
        }
        // 刷新token
        if (response.headers.refreshtoken) {
            store.dispatch('user/setToken', response.headers.refreshtoken)
        }
        return res.data
    },
    error => {
        loadingInstance.close();
        console.error('err', error, error.response.data.msg) // for debug
        ElMessage({
            message: error.response.data.msg,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)
export {VUE_APP_BASE_API,service}